#!/bin/sh

# 设置当有命令错误时立即退出选项
set -e

WORKDIR=$(cd `dirname $0`; pwd)
BASE_FILE=${WORKDIR}/logs
GC_FILE=${BASE_FILE}/gc_logs

# 填写服务名称，当日志文件名称不是以服务名时，手动修改LOGS_FILE为正确的名称
SERVICE=base-config-service
LOGS_FILE=${SERVICE}.log
HTTP_PORT=10001
DUBBO_PORT=20001
WAIT_TIME=2

# 限制JVM启动内存
MIN_RESOURCE=512M
MAX_RESOURCE=1024M
# 启动打印日志级别，t1、t2、t3是info，dev是debug
LOG_LEVEL=t1

function get_date {
    date +%Y-%m-%d\ %H:%M:%S
}

function ENV_MADE {
    mkdir /opt/case/tongyong_conf/apollo -p
    echo "idc=${APOLLO_TAG}" > /opt/case/tongyong_conf/apollo/server.properties
    echo "env=UAT" >> /opt/case/tongyong_conf/apollo/server.properties
    echo "uat_meta=http://t1-managerdaikuan.2345.com:8080" >> /opt/case/tongyong_conf/apollo/server.properties
}


function CHECK_ENV {
# 检查必要的启动参数
echo "`get_date` [PRECHECK] Check the neccessary env to start a app"

# 检查jar包是否存在
echo -en "JAR \t ... "
if [ -f ${WORKDIR}/${SERVICE}.jar ];then
    echo "${SERVICE}.jar"
else
    echo "error"
    echo "${WORKDIR}/${SERVICE}.jar can't be empty, please check ..."
    exit 1
fi

echo -en "APOLLO_TAG ... "
if [ x$APOLLO_TAG == x ];then
    echo "error"
    echo "APOLLO_TAG can't be empty, please check ..."
    exit 1
else
    echo "$APOLLO_TAG"
fi
}


function APP_START {
    CHECK_ENV
    ENV_MADE
    echo "`get_date` [precheck] Excellent, precheck step is pass."
    echo "`get_date` start app now, please wait ... "
    java -server -Xms${MIN_RESOURCE} -Xmx${MAX_RESOURCE} \
        -Dspring.profiles.active=${LOG_LEVEL} -jar ${SERVICE}.jar \
        --server.port=${HTTP_PORT} --spring.profiles.active=${LOG_LEVEL} \
        -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=3 \
        -XX:GCLogFileSize=128M -XX:+PrintGC -XX:+PrintGCDetails \
        -XX:+PrintGCTimeStamps -XX:+PrintTenuringDistribution  > : &
}

function OUTPUT {
while [ ! -f ${BASE_FILE}/$LOGS_FILE ]
do
   sleep $WAIT_TIME
done
tail -F ${BASE_FILE}/$LOGS_FILE
}

function main {
    APP_START
    OUTPUT
}

main
